import config from '../config/index.js';
import { checkUserPermission, saveDifyChatPaylog } from './authService.js';
import { stream } from '../utils/streamUtil.js';

export async function handleDifyRequest(req, res) {
  const body = req.body;
  const headers = req.headers;
  const { appId, appuserId, platform = "agency" } = body;

  // 验证用户权限
  const authResult = await checkUserPermission(appId, appuserId, platform);
  if (!authResult.success) {
    res.status(403).send(authResult.message);
    return;
  }
  const APIkey = authResult.APIkey;
  const fetchAPI = `${config.server.dify}/chat-messages`;
  const {
    conversation_id,
    files = [],
    inputs,
    parent_message_id,
    query,
    response_mode,
  } = body;

  const payload = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${APIkey}`,
    },
    body: JSON.stringify({
      conversation_id,
      files,
      inputs,
      parent_message_id,
      query,
      response_mode,
      user: `${platform}_${appuserId}`,
    }),
  };

  try {
    const response = await fetch(fetchAPI, payload);
    if (response.status !== 200) {
      res.status(response.status).send(response.statusText);
      return;
    }
    res.setHeader("Content-Type", response.headers.get("Content-Type"));

    await stream(response.body, res);
  } catch (error) {
    console.error("API请求错误:", error);
    res.status(500).send(error.message);
  }
}
